<template>
  <div class="additional-form-view" v-loading="loading">
    <!-- start 头部 -->
    <div class="setting-header">
      <div class="left-wrap">
        <p class="setting-back-btn" @click="handleBack">
          <i class="iconfont icon-arrow-left"></i> {{$t('common.base.back')}}
        </p>
        <el-tooltip
          effect="dark"
          :content="$t('event.setting.additional.additionalFormView.tips1')"
          placement="bottom"
        >
          <el-input
            class="setting-back-name"
            v-model="cardName"
            :placeholder="$t('event.setting.additional.additionalFormView.pla1')"
            maxlength="20"
          ></el-input>
        </el-tooltip>
      </div>
      <div class="right-wrap">
        <el-button @click="closeTab">{{$t('common.base.close')}}</el-button>
        <el-button type="primary" @click="handleSubmit" :disabled="pending">{{$t('common.base.save')}}</el-button>
      </div>
    </div>
    <!-- end 头部 -->

    <!-- start 表单设计器 -->
    <div class="setting-main">
      <form-design v-model="fields" :mode="mode"></form-design>
    </div>
    <!-- end 表单设计器 -->
  </div>
</template>

<script>
/* api */
import * as SettingServiceEventApi from '@src/api/SettingServiceEventApi';
/* util */
import * as FormUtil from '@src/component/form/util';
import { parse } from '@src/util/querystring';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
export default {
  name: 'additional-form-view',
  data() {
    return {
      cardId: '', //  当前附加组件标识
      cardName: '', //  当前组件名称
      sourceCardName: '', //  原组件名称(用于返回判断是否修改使用)
      fields: [], //  已设置的表单字段
      mode: 'event_card',
      loading: true, //  页面加载状态
      pending: false, //  保存按钮状态
    };
  },
  methods: {
    /* 保存 */
    async handleSubmit() {
      try {
        // 修改附加组件名称
        if (this.cardName != this.sourceCardName ) {
          await this.updateCardName();
        }

        // 将字段转换成后端可接收的字段
        let fields = FormUtil.toField(this.fields);
        fields.forEach((field, index) => {
          field.cardId = this.cardId;
          field.orderId = index;
        });

        let message = FormUtil.validate(fields);
        if(!FormUtil.notification(message, this.$createElement)) return;

        this.pending = true;

        let result = await SettingServiceEventApi.createBatch(fields);

        let isSuccess = result.status == 0;
        this.$platform.notification({
          type: isSuccess ? 'success' : 'error',
          title: isSuccess ? this.$t('event.setting.additional.additionalFormView.tips2') : this.$t('event.setting.additional.additionalFormView.tips3'),
          message: isSuccess ? null : result.message
        })

        if (isSuccess) {
          setTimeout(() => {
            this.handleBack();
          }, 500)
        } else {
          this.pending = false;
        }
      } catch (error) {
        console.error(error);
        this.pending = false;
      }
    },
    /* 返回 */
    handleBack() {
      let fromId = window.frameElement.getAttribute('fromid');
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);

      // this.$platform.openTab({
      //   id: 'M_SYSTEM',
      //   title: '附加组件设置',
      //   url: '/setting/serviceStation/cardManage',
      //   reload: true,
      //   close: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageServiceStationCardManage,
        reload: false,
      })
    },
    /* 关闭 */
    closeTab() {
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);
    },
    /* 查询附加组件名称 */
    fetchCardName() {
      SettingServiceEventApi.getCardInfo({ id: this.cardId })
        .then(res => {
          const { status, data = {} } = res;
          if (status == 0) {
            this.cardName = data.name;
            this.sourceCardName = data.name;
          }
        })
        .catch(err => console.error(err))
    },
    /* 查询表单字段 */
    fetcCardFields() {
      SettingServiceEventApi.getCardFieldList({ cardId: this.cardId, isFromSetting: true })
        .then(res => {
          let fields = res || [];
          let sortedFields = fields.sort((a, b) => a.orderId - b.orderId);
          this.fields = FormUtil.toFormField(sortedFields);
        })
        .finally(() => {
          this.loading = false;
        })
        .catch(err => console.error(err))
    },
    /* 更新附加组件名称 */
    updateCardName() {
      return SettingServiceEventApi.updateCardInfo({ id: this.cardId, name: this.cardName })
        .then(res => {
          return res;
        })
        .catch(err => console.error(err))
    }
  },
  mounted() {
    let query = parse(window.location.search) || {};
    this.cardId = query.cardId || '';

    this.fetchCardName();
    this.fetcCardFields();
  },
};
</script>

<style lang="scss" scoped>
.additional-form-view {
  height: 100%;
  overflow-y: hidden;
  background: $bg-color-l1;

  .setting-header {
    margin: 12px 12px 0 12px;
    padding: 0px 24px;
    background-color: #fff;
    border-bottom: 1px solid #f4f7f5;
    display: flex;
    justify-content: space-between;
    flex-flow: row nowrap;
    align-items: center;

    .left-wrap {
      display: flex;
      justify-content: flex-start;
      height: 48px;
      line-height: 48px;
      color: $text-color-regular;

      .setting-back-btn {
        display: none;
        width: 90px;
        margin-bottom: 0;
        padding-right: 14px;
        border-right: 1px solid $bg-color-l1;
        cursor: pointer;
      }

      .setting-back-name {
        margin-left: 12px;
        height: 35px;
        ::v-deep .el-input__inner {
          width: 150px;
          border: none;
          border-bottom: 1px dashed $color-primary;
        }
      }
    }
  }

  .setting-main {
    padding: 12px;
    height: calc(100% - 53px);
  }
}
</style>
